<?php

namespace App\Console\Commands\Feishu\Hire;

use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Models\Feishu\FeishuHireApplicationModel;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;

class HireSendNotifyV2Command extends Command
{

    protected $signature = 'feishu:hire-send-notify-v2 {--cycle=weekly}';

    protected $description = '飞书:招聘简历记录周/月推送';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        // 周月推送
        $cycleType = $this->option('cycle');
        switch ($cycleType) {
            case 'monthly':
                $titleTag = '本月';
                $startAt  = Carbon::yesterday()->startOfMonth()->getTimestamp();
                $endAt    = Carbon::yesterday()->endOfMonth()->getTimestamp();
                break;
            case 'yesterday':
                $titleTag = '昨日';
                $startAt  = Carbon::yesterday()->startOfDay()->getTimestamp();
                $endAt    = Carbon::yesterday()->endOfMonth()->getTimestamp();
                break;
            case 'lastWeek':
                $titleTag = '上周';
                $startAt  = Carbon::yesterday()->startOfWeek()->getTimestamp();
                $endAt    = Carbon::yesterday()->endOfWeek()->getTimestamp();
                break;
            case 'weekly':
            default:
                // 获取本周星期一的时间戳
                $titleTag = '本周';
                $startAt  = Carbon::now()->startOfWeek()->getTimestamp();
                $endAt    = Carbon::now()->endOfWeek()->getTimestamp();
                break;
        }

        $todayStartAt = Carbon::yesterday()->startOfDay()->getTimestamp();
        $todayEndAt   = Carbon::yesterday()->endOfDay()->getTimestamp();

        try {
            // 周期内数据
            $dataCycle = self::getFsHireData($startAt, $endAt)['data'];
            // 今日数据
            $dataToday = self::getFsHireData($todayStartAt, $todayEndAt)['data'];
        } catch (\Exception $exception) {
            throw new Exception("招聘数据获取失败, Cookie 失效了");
        }

        // 标题
        $title = '🌟🌟🌟' . " {$titleTag}招聘业绩排行" . date('m月d日', $startAt) . '-' . date('m月d日',
                $endAt) . ' 🌟🌟🌟';


        // 头部
        $header = '🌟🌟' . " 昨日获取简历 {$dataToday['sumRow']['appliCount']} 个 🌟🌟 \r\n🌟🌟 昨日新增offer {$dataToday['sumRow']['appOfferSend']}个 🌟🌟\r\n";
        $header .= '(数据更新于 ' . date('Y-m-d H:i:s', $dataToday['dataVersion'] / 1000) . ' )';

        $dataCycleFormatData = collect(self::formatFsData($dataCycle))
            ->sortByDesc('appliCount')
            ->sortByDesc('interviewRound1Scheduled')
            ->keyBy('name');
        $dataTodayFormatData = collect(self::formatFsData($dataToday))
            ->sortByDesc('appliCount')
            ->keyBy('name');

//        dd($dataCycleFormatData);
        $contentList = [];
        foreach ($dataCycleFormatData as $key => $item) {
            $contentList[$key] = [
                'talentCreatorFsName'      => $item['name'],
                'talentCreatorFsNickname'  => '',
                'newHire'                  => $item['appliCount'],
                'newHireListToday'         => $dataTodayFormatData[$key]['appliCount'] ?? 0,
                'waitInterview'            => $item['interviewRound1Scheduled'],
                'waitInterviewToday'       => $dataTodayFormatData[$key]['interviewRound1Scheduled'] ?? 0,
                'waitInterviewRound2'      => $item['interviewRound2Scheduled'],
                'waitInterviewTodayRound2' => $dataTodayFormatData[$key]['interviewRound2Scheduled'] ?? 0,
                'waitEntry'                => $item['appOfferSend'],
                'waitEntryListToday'       => $dataTodayFormatData[$key]['appOfferSend'] ?? 0
            ];
        }

        // 消息体
        $content = [];

        $loopTimes = 1;
        foreach ($contentList as $key => $item) {
            $contentStr = '';
            switch ($loopTimes) {
                case 1:
                    $contentStr .= '🥇  ';
                    break;
                case 2:
                    $contentStr .= '🥈  ';
                    break;
                case 3:
                    $contentStr .= '🥉  ';
                    break;
            }
            $contentStr .= "{$item['talentCreatorFsName']} \r\n";
//            $contentStr .= "{$item['talentCreatorFsName']} ({$item['talentCreatorFsNickname']}) \r\n";

            $contentStr .= "" . $titleTag . "获取简历：" . ($item['newHire'] ?? 0) . "份（昨日新增：" . ($item['newHireListToday'] ?? 0) . "份）" . PHP_EOL;
            $contentStr .= "" . $titleTag . "预约一面数：" . ($item['waitInterview'] ?? 0) . "个（昨日新增：" . ($item['waitInterviewToday'] ?? 0) . "个）" . PHP_EOL;
            $contentStr .= "" . $titleTag . "预约二面数：" . ($item['waitInterviewRound2'] ?? 0) . "个（昨日新增：" . ($item['waitInterviewTodayRound2'] ?? 0) . "个）" . PHP_EOL;
            $contentStr .= "" . $titleTag . "发送offer：" . ($item['waitEntry'] ?? 0) . "个（昨日新增：" . ($item['waitEntryListToday'] ?? 0) . "个）";
            $content[]  = [
                'tag'  => 'div',
                'text' => [
                    'content' => $contentStr,
                    'tag'     => 'plain_text'
                ]
            ];
            $loopTimes++;
        }


        // 拼装发送数据
        $data             = [
            'elements' => [
                [
                    "tag"     => "markdown",
                    "content" => $header,
                ],
                [
                    "tag" => "hr"
                ]
            ],
            'header'   => [
                'template' => 'blue',
                'title'    => [
                    'tag'     => 'plain_text',
                    'content' => '🎉🎉🎉 ' . $title . ' 🎉🎉🎉',
                ]
            ]
        ];
        $data['elements'] = array_merge($data['elements'], $content);

        $robot = SendFs::newRobot(SendFs::ROBOT_HIRE_NOTIFY);

        if (isTest()) {
            $robot = $robot   // 测试机器人
            ->coverConfig('https://open.feishu.cn/open-apis/bot/v2/hook/9f889f27-876a-4859-8c32-db3ac9edc54f',
                'G0eO4kKzpQviVbvbJzLC2');
        } else {
            $robot = $robot   // 测试机器人
            ->coverConfig('https://open.feishu.cn/open-apis/bot/v2/hook/1401e47f-fe14-44b6-824a-d9357e891377',
                'r5lCWfFbZSqgVeXYpMDLed');
        }

        $robot = $robot
            // 生产机器人

            ->setCardMessageBody($data)
            ->send();
        return 0;
    }

    private function getResumeCount($startAt, $endAt, array $stageType = [], string $timeColumn = 'updatedAt')
    {
        $list = FeishuHireApplicationModel::query()
                                          ->select(DB::raw('count(applicationId) as count, talentCreatorFsId, talentCreatorFsName, talentCreatorFsNickname'))
                                          ->when(count($stageType), function ($query) use ($stageType) {
                                              $query->whereIn('stageType', $stageType);
                                          })
                                          ->whereBetween($timeColumn, [$startAt, $endAt])
                                          ->groupBy('talentCreatorFsId')
                                          ->get();
        return $list;
    }

    private function getFsHireData(int $startAt, int $endAt)
    {
        $config = ConfigModel::query()
                             ->where('module', 'guanyuanDB')
                             ->where('name', 'like', 'feishuHire%')
                             ->first();
        $cookie = $config->value;

        $client  = new Client();
        $headers = [
            'authority'          => 'onepiece-group.feishu.cn',
            'accept'             => 'application/json, text/plain, */*',
            'accept-language'    => 'zh-CN',
            'cache-control'      => 'no-cache',
            'content-type'       => 'application/json',
            'cookie'             => $cookie,
            'origin'             => 'https://onepiece-group.feishu.cn',
            'pragma'             => 'no-cache',
            'referer'            => 'https://onepiece-group.feishu.cn/hire/reports/7220708263875182595/widgets/7220708263879245827',
            'sec-ch-ua'          => '"Chromium";v="106", "Google Chrome";v="106", "Not;A=Brand";v="99"',
            'sec-ch-ua-mobile'   => '?0',
            'sec-ch-ua-platform' => '"macOS"',
            'sec-fetch-dest'     => 'empty',
            'sec-fetch-mode'     => 'cors',
            'sec-fetch-site'     => 'same-origin',
            'user-agent'         => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
            'x-csrf-token'       => '5bnMvDxCyVai_OhlCEqXS1FrVE8NZlFYKJX2_-iIJIc',
            'x-requested-with'   => 'XMLHttpRequest'
        ];
        $body    = '{
  "withAmount": true,
  "reportKey": "7220708263875182595",
  "reportType": "user",
  "widgetKey": "7220708263879245827",
  "measures": [
    {
      "data": null,
      "key": "HrName",
      "rawKey": "HrName"
    },
    {
      "data": null,
      "key": "appliCount",
      "rawKey": "appliCount"
    },
    {
      "data": null,
      "key": "interviewRound1Scheduled",
      "rawKey": "interviewRound1Scheduled"
    },
    {
      "data": null,
      "key": "interviewRound2Scheduled",
      "rawKey": "interviewRound2Scheduled"
    },
    {
      "data": null,
      "key": "appOfferSend",
      "rawKey": "appOfferSend"
    }
  ],
  "dimensions": [
    {
      "key": "hr"
    }
  ],
  "orders": [],
  "filters": {
    "values": {
      "jobProcess": [
        "6977190259583453476"
      ],
      "jobRange": [
        "all"
      ],
      "jobStatus": [
        "1"
      ],
      "operationTime": [
        "' . ($startAt * 1000) . '",
        "' . ($endAt * 1000) . '"
      ]
    },
    "meta": []
  },
  "withSum": true,
  "showZeroRow": false,
  "shareOwnerData": 1,
  "fromReportKey": "7220708263875182595",
  "limit": 50,
  "offset": 0
}';
        $request = new Request('POST',
            'https://onepiece-group.feishu.cn/atsx/api/report/selfhelp/widget/data?type=table', $headers, $body);
        $res     = $client->sendAsync($request)->wait();
        $data    = $res->getBody();
        return json_decode($data, 1);

    }

    private function formatFsData($data): array
    {
        $rows = $data['rows'] ?? [];

        $returnList = [];
        foreach ($rows as $row) {
            $hrInfo       = json_decode($row['HrName'], 1);
            $returnList[] = [
                'name'                     => $hrInfo['name'],
                'appliCount'               => $row['appliCount'],
                'interviewRound1Scheduled' => $row['interviewRound1Scheduled'],
                'interviewRound2Scheduled' => $row['interviewRound2Scheduled'],
                'appOfferSend'             => $row['appOfferSend']
            ];
        }

        return $returnList;
    }
}
